
const express = require('express');
const cors = require('cors');

// const testData = require("./test.json")
// const test = require("./test")

const mysql = require('mysql2');
const bodyParser = require('body-parser');

require('dotenv').config();
const router = express.Router();

// 创建一个连接池
const db_host =  process.env.DB_HOST
const db_user = process.env.DB_USER
const db_password = process.env.DB_PASS
const db_database =  process.env.DB_NAME

const pool = mysql.createPool({
    host: db_host,       // MySQL服务器地址
    user: db_user,               // MySQL用户名
    database: db_database,      // 要连接的数据库名
    password: db_password,       // MySQL密码
    port: 3306,              // MySQL服务器端口

    connectionLimit: 10,      // 连接池中允许的最大连接数
    waitForConnections: true, // 如果没有可用连接，队列等待而不是拒绝
    queueLimit: 0,             // 连接请求排队的最大数量，默认为 0，无限制
    connectTimeout: 10000,    // 连接超时时间（毫秒）
    //acquireTimeout: 10000,    // 从连接池获取连接的超时时间（毫秒）
  });

router.use(cors());
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
  

//用户登录
router.post("/login",(req,res)=>{
    console.log(req.body)
    const {username,password} = req.body;
    let isLogin = false;

    userLoginSql = "select * from user_tb where username = '" + username + "' and password = '"+password+"'"  

    console.log("##### userLoginSql is =====>："+userLoginSql)
    pool.query(userLoginSql, (err, result) => {
        if (err) {
            console.log(err)
            res.json({ err: err, msg: '注册用户失败', code: 500 })
            return
        }
        console.log(result);
        console.log(result.length)
        if(result.length >=1){
            isLogin = true
            res.json({ msg: '注册登录成功', data:{isLogin:isLogin},code: 200 })
        }else{
            isLogin = false
            res.json({ msg: '用户名密码不匹配', data:{isLogin:isLogin},code: 200 })
        }
    })
});

//检查是否已经被注册
router.post("/checkusername",(req,res)=>{
    console.log(req.body)
    const {username,password} = req.body;
    let isLogin = false;

    userLoginSql = "select * from user_tb where username = '" + username + "'"  
    userLoginSql
    console.log("#####  checkusername  is =====>："+userLoginSql)
    pool.query(userLoginSql, (err, result) => {
        if (err) {
            console.log(err)
            res.json({ err: err, msg: '检查失败', code: 500,haseUsername:true })
            return
        }
        console.log(result.length)
        if(result.length >=1){
            isLogin = true
            res.json({ msg: '该用户名已经存在', code: 200,haseUsername:true })
        }else{
            isLogin = false
            res.json({ msg: '该用户名没被注册，你可以使用',code:200,haseUsername:false})
        }
    })
});



//用户注册
router.post("/register", (req, res) => {
    console.log(req.body)
    //插入数据库 
    var sql = "insert into user_tb ("
        + "`username`,"
        + "`password`,"
        + "`email`,"
        + "`create_time`,"
        + "`update_time`) values(?,?,?,?,?) "

    console.log("sql is: " + sql)

    const { username, password, email } = req.body

    var isLogin = false
    var create_time = new Date();
    var updateTime = new Date();

    var fields = [username, password, email, create_time, updateTime]

    pool.query(sql, fields, (err, result) => {
        if (err) {
            console.log(err)
            res.json({ err: err, msg: '注册用户失败', code: 500 ,isLogin:false})
            return
        }
        console.log("insert table ok")
        res.json({ msg: '注册用户成功', code: 200,isLogin:true })
    })
});

module.exports = router